﻿using FlexFlow.Base.Application;
using FlexFlow.Base.Interface;
using FlexFlow.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FlexFlow.Runtime.Applications
{
    /// <summary>
    /// 为任务节点提供应用程序
    /// </summary>
    public class TaskApplication : AbstractApplication
    {
        public override void OnExecute(ApplicationInvokeContext context, ApplicationExecuteResult result)
        {
            WorkFlowTaskFactory factory = this.CreateTaskFactory();
            List<WorkFlowTask> tasks = new List<WorkFlowTask>();
            if (context.Operators != null)
            {
                //绑定操作员到任务工厂中
                factory.AddRecivers(context.Operators);
            }
            //为审批任务绑定处理器
            factory.BindProcessor(OnTaskSubmit);

            Dictionary<string, string> options = context.ActivityOptions.ToDictionary(m => m.Key, m => m.Value);
            factory.AddSendData(SystemTaskDataKey.NeedSignOption,
                options.ContainsKey(SystemTaskDataKey.NeedSignOption) ? bool.Parse(options[SystemTaskDataKey.NeedSignOption]) : false);
            if (options.ContainsKey(SystemTaskDataKey.TaskFormId))
            {
                factory.AddSendData(SystemTaskDataKey.TaskFormId, Guid.Parse(options[SystemTaskDataKey.TaskFormId]));
            }
            if (options.ContainsKey(SystemTaskDataKey.ExtendButton))
            {
                factory.AddSendData(SystemTaskDataKey.ExtendButton, options[SystemTaskDataKey.ExtendButton]);
            }
            //创建审批任务并加入到任务列表中
            tasks.Add(factory.CreateApprovalTask());

            //返回结果
            result.NextActivityIds = context.NextPaths.Select(m => m.To).ToArray();
            result.SendTasks = tasks.ToArray();
        }

        public override void OnTaskSubmit(ApplicationInvokeContext context, WorkFlowTask task, TaskSubmitResult result)
        {
            bool acc = (bool)task.SubmitData["Accepted"];
            Dictionary<string, string> options = context.ActivityOptions.ToDictionary(m => m.Key, m => m.Value);
            bool needSignOption = options.ContainsKey(SystemTaskDataKey.NeedSignOption) ? bool.Parse(options[SystemTaskDataKey.NeedSignOption]) : false;
            if (needSignOption)
            {
                result.Message = "意见：" + task.SubmitData[SystemTaskDataKey.NeedSignOption];
            }
            //返回结果
            result.IsAccept = true;
            string conditionVal = acc ? "同意" : "不同意";
            Guid[] nextActs = GetConditionMatchedPath(context.NextPaths, "审批结果", conditionVal)
                .Select(m => m.To)
                .ToArray();
            if (nextActs.Length == 0)
            {
                throw new Exception("活动未指定" + conditionVal + "后的操作，无法提交！");
            }
            result.NextActivityIds = nextActs;
        }
    }
}
